package com.yisu.expressway.onedollar.activity;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.LogisticsInfoObj;
import com.yisu.expressway.onedollar.model.TraceItem;
import com.yisu.expressway.onedollar.widget.DashLine;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.SpannableUtil;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Kaven on 2016/12/27.
 */

public class OrderExpressActivity extends BasicActivity
        implements PagingRecyclerView.SampleActionListener {
    private static final String EXTRA_KEY_ORDER_ID = "extra_key_order_id";
    private static final String EXTRA_KEY_GOODS_PIC = "extra_key_goods_pic";
    @Bind(R.id.rootView)
    protected View mRootView;
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mRecyclerView;
    @Bind(R.id.iv_company_logo)
    protected ImageView mCompanyLogoIv;
    @Bind(R.id.tv_company_name)
    protected TextView mCompanyNameTv;
    @Bind(R.id.tv_logistics_num)
    protected TextView mLogisticsNumTv;
    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;
    private LogisticsInfoObj mLogisticsInfoObj;

    public static void launch(Context context, long orderId, String goodsPic) {
        Intent intent = new Intent(context, OrderExpressActivity.class);
        intent.putExtra(EXTRA_KEY_ORDER_ID, orderId);
        intent.putExtra(EXTRA_KEY_GOODS_PIC, goodsPic);
        context.startActivity(intent);
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_onedollar_express;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void releasePresenter() {

    }
    private long mOrderId;
    private String mGoodsPic;
    @Override
    protected void getIntentData(Intent intent) {
        long longExtra = intent.getLongExtra(EXTRA_KEY_ORDER_ID, -1);
        if (longExtra <= 0){
            finish();
        }
        mOrderId = longExtra;
        mGoodsPic = intent.getStringExtra(EXTRA_KEY_GOODS_PIC);
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(this,
                LinearLayoutManager.VERTICAL);
        mRecyclerView.init(mListDivider, new LinearLayoutManager(this), this, 20);
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    private View createHeaderView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        if (mAnimation != null) {
                            mAnimation.start();
                        }

                        mRecyclerView.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }

    @Override
    public void fetchData(int start, int pageSize) {
        getLogisticsInfo();
    }

    public void refreshView(boolean bSuc) {
        if (bSuc) {
            mRootView.setVisibility(View.VISIBLE);
            setCompanyView();
        } else {
            mRootView.setVisibility(View.GONE);
        }
    }

    private void setCompanyView() {
        if (mLogisticsInfoObj == null) {
            return;
        }
        mCompanyLogoIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        String format = String.format(getString(R.string.one_dollar_express_company),
                mLogisticsInfoObj.shipperName);
        mCompanyNameTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 5),
                R.color.oneDollarTextGrey));
        format = String.format(getString(R.string.one_dollar_express_num),
                mLogisticsInfoObj.logisticCode);
        mLogisticsNumTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 5),
                R.color.oneDollarTextGrey));
        if (!TextUtils.isEmpty(mGoodsPic)) {
            String[] split = mGoodsPic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(this).load(picShow).asBitmap().placeholder(R.drawable.blank)
                    .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                    .animate(R.anim.fade_in_image).into(mCompanyLogoIv);
            }
        }else {
            mCompanyLogoIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }
    }

    private void getLogisticsInfo() {
        if (mOrderId <= 0){
            return;
        }
        Map<String, Object> params = new HashMap();


        params.put("orderId", mOrderId);
        ApiClientHelper.postApi(ApiSetting.getLogisticsInfo(), new TypeToken<LogisticsInfoObj>() {
        },  new JSONObject(params), new Response.Listener<ApiResult<LogisticsInfoObj>>() {
            @Override
            public void onResponse(ApiResult<LogisticsInfoObj> result) {
                if (!result.success) {
                    refreshView(false);
                    return;
                }
                LogisticsInfoObj result1 = result.getResult();
                if (result1 != null) {
                    mLogisticsInfoObj = result.getResult();
                }
                refreshView(true);
                mRecyclerView.dataFetchDone(mLogisticsInfoObj.traces);
                if (mAnimation != null) {
                    mRefreshLayout.setRefreshing(false);
                    mAnimation.stop();
                    carImage.setImageResource(R.color.colorTransparent);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                refreshView(false);
            }
        }, this);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(this).inflate(R.layout.logisticsinfo_item_list, null);
        return new LogisticsInfoViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final LogisticsInfoViewHolder holder = (LogisticsInfoViewHolder) _holder;
        final TraceItem item = (TraceItem) _item;
        holder.acceptTimeTv.setText(item.AcceptTime);
        holder.acceptStationTv.setText(item.AcceptStation);
        if (mLogisticsInfoObj != null){
            if (mLogisticsInfoObj.state == LogisticsInfoObj.STATE_SIGN){
                holder.lineDot.setBackground(getResources().getDrawable(R.drawable.banner_indicater_dot_normal_blue));
                holder.lineDash.setColor(getResources().getColor(R.color.oneDollarCommon));
            }else {
                holder.lineDot.setBackground(getResources().getDrawable(R.drawable.banner_indicater_dot_normal));
                holder.lineDash.setColor(getResources().getColor(R.color.oneDollarTextGrey));
            }
        }
    }

    class LogisticsInfoViewHolder extends BaseRvAdapter.SampleViewHolder {
        @Bind(R.id.line_dot)
        View lineDot;
        @Bind(R.id.line_dash)
        DashLine lineDash;
        @Bind(R.id.tv_accepttime)
        TextView acceptTimeTv;
        @Bind(R.id.tv_acceptstattion)
        TextView acceptStationTv;
        public LogisticsInfoViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
